﻿using FlexFlow.Model;
using FlexFlow.MVC.Models.JsTree;
using FlexFlow.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FlexFlow.MVC.Controllers
{
    /// <summary>
    /// 表示组织机构管理API控制器
    /// </summary>
    [Auth(AuthType.API)]
    public class OrganizeAPIController : Controller
    {
        /// <summary>
        /// 创建一个组织机构
        /// </summary>
        /// <param name="parentOrg">
        /// 该组织机构的父级组织机构
        /// </param>
        /// <returns>
        /// 创建的组织机构
        /// </returns>
        public ActionResult Create(string name, string orgType, Guid? parentOrg = null)
        {
            return Json(OrganizeManager.Default.Create(orgType, name, parentOrg));
        }
        /// <summary>
        /// 删除具有指定Id的组织机构实体以及其下所有的组织机构
        /// </summary>
        /// <param name="id">
        /// 要删除的组织机构实体ID
        /// </param>
        /// <returns>
        /// 删除结果
        /// </returns>
        public ActionResult Delete(Guid id)
        {
            return Json(OrganizeManager.Default.Delete(id));
        }
        /// <summary>
        /// 重命名指定组织机构
        /// </summary>
        /// <param name="orgId">
        /// 要重命名的组织机构Id
        /// </param>
        /// <param name="newName">
        /// 要重命名的组织机构的新名称
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult Rename(Guid org, string newName)
        {
            return Json(OrganizeManager.Default.Rename(org, newName));
        }
        /// <summary>
        /// 重新设定指定组织机构的父组织机构
        /// </summary>
        /// <param name="org">
        /// 要设定的组织机构
        /// </param>
        /// <param name="parGuid">
        /// 要设定的组织机构的父组织机构
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult SetParent(Guid org, Guid? parGuid)
        {
            return Json(OrganizeManager.Default.SetParent(org, parGuid));
        }
        /// <summary>
        /// 取得组织机构数据列表
        /// </summary>
        /// <param name="formatToFuelux">
        /// 表示返回的结果是否格式化为Fuelux的数据格式
        /// </param>
        /// <param name="parentOrg">
        /// 要取得列表的父级组织机构
        /// </param>
        /// <param name="containsMember">
        /// 表示是否取得父组织机构下的所有成员
        /// </param>
        /// <returns>
        /// 取得的数据列表
        /// </returns>
        public ActionResult GetList(bool formatToFuelux = true, Guid? parentOrg = null, bool containsMember = false)
        {
            //取得子组织机构列表
            OperateResult res = OrganizeManager.Default.GetList(parentOrg);
            if (res.ResultCode != 200 || formatToFuelux == false)
            {
                return Json(res);
            }

            //重新封装结果
            List<Item> items = new List<Item>();
            List<Organization> orgs = (List<Organization>)res.Tag;
            foreach (var org in orgs)
            {
                Item item = new Item()
                {
                    id = org.Identity,
                    text = org.Name,
                    children = true,
                    data = org,
                    type = org.OrganizationType
                };
                items.Add(item);
            }

            //包含成员
            if (containsMember)
            {
                if (parentOrg == null)
                {
                    return Json(new OperateResult()
                    {
                        ResultCode = 500,
                        Message = "参数错误，containMember为真时必须指定parentOrg"
                    });
                }

                //取得成员列表
                List<UserRelation> relations = DefaultComponentSettings.UserRelationProvider.GetRelations((Guid)parentOrg);

                //封装结果
                foreach (var rel in relations)
                {
                    User linkedUser = DefaultComponentSettings.UserProvider.Get(rel.Member);
                    if (linkedUser == null)
                    {
                        return Json(new OperateResult()
                        {
                            ResultCode = 500,
                            Message = "发现意外关系，放弃操作,ID为 " + rel.Member + "的用户不存在！关系ID为 " + rel.Identity
                        });
                    }
                    items.Add(new Item()
                    {
                        children = false,
                        type = "成员",
                        data = new { id = linkedUser.Identity },
                        id = rel.Identity,
                        text = linkedUser.Name
                    });
                }
            }
            return Json(items);
        }
        /// <summary>
        /// 向指定的组织机构中加入指定的成员
        /// </summary>
        /// <param name="orgId">
        /// 要加入成员的组织机构ID
        /// </param>
        /// <param name="userAccount">
        /// 要加入的成员账号
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult AddMember(Guid orgId, string account)
        {
            return Json(UserRelationManager.Default.AddMember(orgId, account));
        }
        /// <summary>
        /// 创建并添加组织机构成员
        /// </summary>
        /// <param name="orgId">
        /// 要添加组织机构成员的组织机构ID
        /// </param>
        /// <param name="name">
        /// 组织机构成员的名称
        /// </param>
        /// <param name="account">
        /// 组织机构成员的登录账号
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult CreateAndAddMember(Guid orgId, string name, string account, string password = "123456789")
        {
            return Json(UserRelationManager.Default.CreateAndAddMember(orgId, name, account, password));
        }
        /// <summary>
        /// 更新指定组织机构的信息
        /// </summary>
        /// <param name="orgId">
        /// 组织机构ID
        /// </param>
        /// <param name="name">
        /// 组织机构名称
        /// </param>
        /// <param name="type">
        /// 组织机构类型
        /// </param>
        /// <param name="leaders">
        /// 组织机构领导
        /// </param>
        /// <param name="chargeLeaders">
        /// 组织机构分管领导
        /// </param>
        /// <param name="locked">
        /// 组织机构是否被锁定
        /// </param>
        /// <returns>
        /// 更新结果
        /// </returns>
        public ActionResult Update(Guid orgId, string name = null, string type = null, string leaders = null, string chargeLeaders = null, string locked = "")
        {
            return Json(OrganizeManager.Default.Update(orgId, name, type, leaders, chargeLeaders, locked == "on" ? true : false));
        }
        /// <summary>
        /// 查询名称中包含指定字符的表单模板集合
        /// </summary>
        /// <param name="nameLike">
        /// 要查询的表单模板名称
        /// </param>
        /// <param name="skip">
        /// 返回数据的起始位置
        /// </param>
        /// <param name="limit">
        /// 限制数量
        /// </param>
        /// <returns>
        /// 查询结果
        /// </returns>
        public ActionResult QueryByName(string nameLike, int skip = 0, int limit = 5)
        {
            OperateResult res = OrganizeManager.Default.QueryByName(nameLike, skip, limit);
            if (res.ResultCode != 200)
            {
                return Json(res);
            }
            else
            {
                List<object> tempList = new List<object>();
                foreach (var item in (List<Organization>)res.Tag)
                {
                    tempList.Add(new { name = item.Name, id = item.Identity });
                }
                return Json(tempList, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 取得指定Id对应的组织机构实体
        /// </summary>
        /// <param name="orgId">
        /// 组织机构id
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult GetById(Guid orgId)
        {
            return Json(OrganizeManager.Default.Get(orgId));
        }
    }
}
